<!-- 采购合同编辑 -->
<template>
  <div class="registerDetail">
    <van-nav-bar :title="$route.meta.title" left-text="返回" left-arrow :fixed="true" :placeholder="true" @click-left="$router.go(-1)" />
    <!-- 表单 -->
    <div class="formData">
      <van-form ref="form">
        <van-field readonly v-model="formData.billNumber" name="采购发票单编号" label="采购发票单编号" input-align="right" placeholder="请输入" />

        <van-field v-model="formData.bizDate" name="会计记账日期" label="会计记账日期" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelectTime('bizDate')" readonly />
        <van-field v-model="formData.signCompany" readonly name="签约公司" label="签约公司" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelect('signCompanyId', 'signCompany')" />
        <van-field v-model="formData.SHSupplier" name="二手车供应商" label="二手车供应商" input-align="right" placeholder="请输入" />
        <van-field required name="radio" label="到票客户类型" input-align="right">
          <template #input>
            <van-radio-group v-model="formData.customerType" direction="horizontal">
              <van-radio :name="item.value" v-for="(item, index) in isflagList" :key="index">{{ item.name }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field required v-model="formData.remark" name="备注" label="备注" type="textarea" input-align="left" placeholder />

        <div class="car_title">车辆信息</div>

        <van-field v-model="formData.vinCode" readonly name="车架号" label="车架号" input-align="right" placeholder="请选择" />

        <van-field v-model="formData.property" name="属性" label="属性" input-align="right" placeholder="请输入" readonly></van-field>
        <van-field v-model="formData.taxRate" name="税率" label="税率" input-align="right" placeholder="请输入" />
        <van-field v-model="formData.Amount" name="折后金额" label="折后金额" input-align="right" placeholder="请输入" />
        <div class="car_title">开票发票信息</div>

        <div v-for="(item, index) in formData.invoiceEntryList">
          <div class="pur_item">
            <div class="pur_title">发票{{ index + 1 }}</div>
            <div class="delBtn" @click="delPur">删除</div>
          </div>
          <van-field v-model="item.invoiceNo" name="发票号码" label="发票号码" input-align="right" placeholder="请输入" />
          <van-field v-model="item.invoiceDate" name="发票日期" label="发票日期" input-align="right" placeholder="请选择" right-icon="arrow" @click="handleSelectTime('invoiceDate', index)" readonly />

          <van-field v-model="item.allAmount" name="含税金额" label="含税金额" input-align="right" placeholder="请输入" />

          <van-field v-model="item.taxRateInvoice" name="税率（%）" label="税率（%）" input-align="right" placeholder="请输入" />
        </div>
        <div class="addBtn" @click="addPur">+添加发票</div>

        <!-- 下拉选择弹窗 -->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-field name="模糊查询" v-if="likeWhoField == 'signCompanyId'" input-align="left" v-model="likeWho" label="模糊查询" placeholder="请输入模糊查询关键词" />
          <van-picker show-toolbar :columns="columns" @confirm="handleSelectConfirm" @cancel="showSelectPicker = false" value-key="name" />
        </van-popup>

        <!-- 时间选择弹窗 -->
        <van-popup v-model="showTimerPicker" position="bottom">
          <van-datetime-picker v-model="currentDate" type="date" @confirm="onTimeConfirm($event)" @cancel="showTimerPicker = false" :formatter="formatter" />
        </van-popup>
        <div class="footerBtn">
          <div class="saveBtn" @click="formOnSubmit(1)">保存</div>
          <div class="submitBtn" @click="formOnSubmit(2)">提交</div>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import {
  Search,
  Empty,
  Field,
  Form,
  Uploader,
  DatetimePicker,
  Tab,
  Tabs,
  Notify
} from "vant";
import { getCookies } from "@/utils/util.js";
import sellManageApi from "@/api/sellManageApi";
import commonApi from "@/api/commonApi";
export default {
  name: "PaymentOrderEdit",
  components: {
    Search,
    Empty,
    Field,
    Form,
    Uploader,
    DatetimePicker,
    Tab,
    Tabs,
    Notify
  },
  data() {
    return {
      showTimerPicker: false,
      formData: {
        saveOrSubmit: "", //固定值,save是保存动作,submit是提交
        billId: "", //单据Id
        billNumber: "", //单据编号
        bizDate: "", //做账日期
        billStatus: "", //单据状态
        brand: "", //所属品牌
        showOrgName: "", //所属展厅
        signCompany: "", //开票公司
        signCompanyId: "", //开票公司
        customerName: "", //客户
        carbuyer: "", //乙方买受人
        carSalePrice: "", //车辆售价含佣金
        carSaleNoTaxPrice: "", //车辆售价不含税额
        qualityPrice: "", //精品售价
        qualityNoTaxPrice: "", //精品售价不含税额
        qualityGuidePrice: "", //精品指导价
        customerType: "", //发票客户类型
        cusType: "", //车主类型
        remark: "", //备注
        allAmount: "",
        Amount: "",
        invoiceEntryList: [
          {
            invoiceNo: "", //发票号码,必填，String
            invoiceDate: "", //发票日期,必填，String
            allAmount: "", //含税金额,必填，String
            taxRateInvoice: "" //税率,必填，String
          }
        ]
      },
      orderId: "",
      billNumber: "",

      columns: [],
      showSelectPicker: false,
      detailId: "",
      userId: getCookies("userId"), //用户ID，必填，String
      isflagList: [
        { name: "个人", value: "01" },
        { name: "公司", value: "02" }
      ],
      currentDate: new Date(),
      showOrgList: [],
      issureTypeList: [],
      fixcenterList: [],
      wareHouseList: [],
      stockTransInsureTypeList: [],
      showCompanyList: [],
      likeWhoField: "",
      likeWho: ""
    };
  },
  watch: {
    likeWho: function(nval, oval) {
      if (nval) {
        let newArr = this.showCompanyList.filter(item => {
          return item.name.indexOf(nval) > -1;
        });
        console.log(newArr);
        this.columns = newArr;
      } else {
        this.columns = this.showCompanyList;
      }
    }
  },
  mounted() {
    this.getCompanyOrgUnit();
    if (this.$route.query) {
      this.detailId = this.$route.query.billId;
      this.getDetail(this.detailId);
      this.orderId = this.$route.query.orderId;
      this.billNumber = this.$route.query.billNumber;
    }
  },
  methods: {
    getDetail(billId) {
      sellManageApi
        .secondHandCarFacade({
          billId,
          method: "getPurchaeInvoiceById"
        })
        .then(res => {
          if (res.code == 1) {
            for (const key in res.data) {
              if (res.data[key] == null || res.data[key] == undefined) {
                res.data[key] = "";
              }
            }
            this.formData = res.data;
            console.log(this.formData);
          }
        });
    },
    // 获取签约公司
    getCompanyOrgUnit() {
      sellManageApi
        .secondHandCarFacade({
          method: "getComponyOrgUnit"
        })
        .then(res => {
          if (res.code == 1) {
            this.showCompanyList = res.data;
          }
        });
    },
    // 投保类型
    getStockTransInsureType() {
      commonApi
        .getEnums({
          key: "stockTransInsureType",
          userId: this.userId
        })
        .then(res => {
          if (res.data) {
            let data = [];
            res.data.forEach((item, index) => {
              if (item.name) {
                data.push(item);
              }
            });
            this.stockTransInsureTypeList = data;
          }
        });
    },

    // 选择下拉
    handleSelect(field, fieldName) {
      this.showSelectPicker = true;
      if (field == "inWarehouseId") {
        this.columns = this.wareHouseList;
      } else if (field == "departMentOrgNameId") {
        this.columns = this.showOrgList;
        // 缺少品牌接口
      } else if (field == "fixCenterId") {
        this.columns = this.fixcenterList;
      } else if (field == "showOrgId") {
        this.columns = this.showOrgList;
      } else if (field == "signCompanyId") {
        this.columns = this.showCompanyList;
      }
      this.likeWhoField = field;
      this.field = field;
      this.fieldName = fieldName;
    },
    // 选择下拉确认
    handleSelectConfirm(value, index) {
      if (this.field == "showOrgId" || this.field == "signCompanyId") {
        this.formData[this.field] = value.billId;
        this.formData[this.fieldName] = value.name;
      } else {
        this.formData[this.field] = value.value;
        this.formData[this.fieldName] = value.name;
      }

      this.showSelectPicker = false;
    },

    onConfirm(val, field) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.formData[field] = `${year}-${month}-${day}`;
      this.showTimerPicker = false;
    },

    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      } else if (type === "hour") {
        return `${value}时`;
      } else if (type === "minute") {
        return `${value}分`;
      } else if (type === "second") {
        return `${value}秒`;
      }
      return value;
    },
    // 时间选择
    handleSelectTime(field, index) {
      this.timeField = field;
      this.showTimerPicker = true;
      this.timeIndex = index;
    },
    onTimeConfirm(val) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.formData.invoiceEntryList[this.timeIndex][
        this.timeField
      ] = `${year}-${month}-${day} `;
      this.showTimerPicker = false;
    },
    //维修预约
    applyRepair() {
      this.$router.push("/applyRepair");
    },
    // 获取list名称
    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter(item => {
          return item[key] == val;
        });
        if (obj.length > 0) {
          return obj[0].name;
        }
      }
      return null;
    },

    formOnSubmit(type) {
      this.$refs.form
        .validate()
        .then(() => {
          sellManageApi
            .secondHandCarFacade({
              ...this.formData,
              method: "updatePurchaeInvoice",
              saveOrSubmit: type == 1 ? "save" : "submit"
            })
            .then(res => {
              console.log(res);
              if (res.code == 1) {
                console.log(res.code);

                if (type == 1) {
                  Notify({ type: "success", message: "保存成功" });
                } else {
                  Notify({ type: "success", message: "提交成功" });
                  this.$router.go(-1);
                }
              }
            });
          this.loading = true;
        })
        .catch(() => {
          this.loading = false;
          this.$toast.fail("请完善信息");
        });
    },

    // 增加发票
    addPur() {
      this.formData.invoiceEntryList.push({
        invoiceNo: "", //发票号码,必填，String
        invoiceDate: "", //发票日期,必填，String
        allAmount: "", //含税金额,必填，String
        taxRateInvoice: "" //税率,必填，String
      });
    },
    // 删除发票
    delPur(index) {
      this.formData.invoiceEntryList.splice(index, 1);
    }
  }
};
</script>

<style lang="less" scoped>
body {
  background: #f3f3f3;
}
.flex {
  display: flex;
  align-items: center;
}
.registerDetail {
  overflow: hidden;
  .detail_header {
    justify-content: space-between;
    margin: 10px 10px;
    border-radius: 5px;
    background: #fff;
    padding: 15px;
    .detail_header_lt {
      .carNo {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 10px;
        .carStatus {
          border: 1px solid #35bc04;
          color: #35bc04;
          border-radius: 5px;
          padding: 5px 5px;
          font-size: 0.24rem;
          text-align: center;
          margin-left: 5px;
        }
      }
      .hank {
        font-size: 14px;
        color: #666;
        .name {
          border-right: 2px solid #ccc;
          padding-right: 5px;
          margin-right: 5px;
        }
      }
    }
    .detail_header_rt {
      justify-content: flex-start;
      .txt {
        font-size: 14px;
        color: #161616;
      }
      .icon-tel {
        color: #fff;
        background: #35bc04;
        font-size: 16px;
        padding: 5px;
        border-radius: 50%;
        margin-right: 5px;
      }
    }
  }
  .formData {
    background: #fff;
    overflow: hidden;
  }
}

.footerBtn {
  display: flex;
  justify-content: space-between;
  width: 80%;
  margin: auto;
  padding-bottom: 50px;
  background: #fff;
  margin-top: 25px;
  .saveBtn {
    background: #ccc;
    color: #fff;
    width: 45%;
    margin: auto;
    text-align: center;
    padding: 12px;
    border-radius: 5px;
    font-size: 15px;
    margin-right: 10px;
  }
  .submitBtn {
    background: #409eff;
    color: #fff;
    width: 45%;
    margin: auto;
    text-align: center;
    padding: 12px;
    border-radius: 5px;
    font-size: 15px;
  }
}
.car_title {
  padding: 10px;
  font-size: 15px;
  font-weight: bold;
  color: #333;
}
.addBtn {
  color: #409eff;
  text-align: center;
  font-size: 16px;
}
.pur_item {
  font-size: 15px;
  color: #409eff;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .pur_title {
    color: #409eff;
  }
  .delBtn {
    color: red;
    font-size: 14px;
  }
}
</style>
